import re
import gtk
import main
import server
import socket
import LaTeX
import TCPClient
import chat_list
import contact_list

class WndChat:
    
    def __init__(self, iter, uname, ip, is_open, socket = None):
        self._builder = gtk.Builder()
        self._builder.add_from_file("chat.glade")
        self._builder.connect_signals(self)
        
        self.iter      = iter
        self.username  = uname
        self.socket    = socket
        self.ip        = ip
        self.is_open   = is_open
        self.status    = False
        
        self.history         = list()
        self.hindex          = 0
        self.is_tex_tag_open = False

        self.chat = self._builder.get_object("tb_chat")
        self.msg  = self._builder.get_object("tb_msg")
        self.sb   = self._builder.get_object("sb_chat_status")
                
        self._obj = self._builder.get_object("wnd_chat")
        self._obj.set_title("Chat with " + self.username)
        self.sb.push(0, "Connecting to " + self.username + "...")
        self._obj.show_all()
        
        chat_list.append(self)

    def inject_data(self, data):
        #print server.username + " is receiving data"
        
                 # Make sure that text is added at the end of the buffer
        #self.chat.place_cursor(self.chat.get_iter_at_offset(self.chat.get_char_count()))
        self.chat.place_cursor(self.chat.get_end_iter())
        self.chat.insert_at_cursor(self.username + " says: ")
        
        LaTeX.parse(data, self.chat)
        
        self.chat.place_cursor(self.chat.get_end_iter())
        self.chat.insert_at_cursor("\n")
        
        if not self._obj.is_active():
            self._obj.set_urgency_hint(True)
        
    def push_status(self, data):
        self.sb.push(0, data)

########################################################################
##                                                                    ##
##  SIGNAL HANDLERS                                                   ##
##                                                                    ##
########################################################################
    
    def on_cmd_chat_send_clicked(self, widget, data = None):
        data = self.msg.get_text(self.msg.get_start_iter(), self.msg.get_end_iter(), False)
        if data == "": return

        if not self.status:
            client_thread = TCPClient.ClientThread(self.iter, self.username, self.ip, True, data)
            client_thread.start()
            
        else:
            self.socket.send(data)
        
        #print server.username + " is sending data"
    
        text = self.msg.get_text(self.msg.get_start_iter(), self.msg.get_end_iter(), False)
        
                 # Make sure that text is added at the end of the buffer
        self.chat.place_cursor(self.chat.get_end_iter())
        self.chat.insert_at_cursor(server.username + " says: ")
        
        LaTeX.parse(data, self.chat)
        
        self.chat.place_cursor(self.chat.get_end_iter())
        self.chat.insert_at_cursor("\n")
        
        if (len(self.history) > 0) and (not self.history[-1][0]): self.history.pop()
        self.history.append([True, data])
        if len(self.history) > 50: self.history.pop(0)
        self.hindex = len(self.history)
        self.msg.set_text("")
        
    def on_wnd_chat_delete_event(self, widget, data = None):
        if self.status:
            self.socket.send("/close " + server.username)
            self.status = False
            self.socket.close()
            
        if self.iter == None:
            iter = main.ls_cl.get_iter_first()
            
            while (main.ls_cl.get_value(iter, 0) != self.username) and (iter != None):
                iter = main.ls_cl.iter_next(iter)
            
                        # The contacting user is not present in the list
        if self.iter != None:
            contact_list._list.set(self.iter, 4, False)
        
        chat_list.remove(self.username)
        
    def on_tb_chat_changed(self, widget, data = None):
        txt_chat = self._builder.get_object("txt_chat_chat")
        txt_chat.scroll_mark_onscreen(self.chat.get_insert())
        
    def on_wnd_chat_focus_in_event(self, widget, data = None):
        if self._obj.get_urgency_hint():
            self._obj.set_urgency_hint(False)

    def on_txt_chat_message_key_press_event(self, widget, event, data = None):
        if event.type == gtk.gdk.KEY_PRESS:
            if event.state & gtk.gdk.CONTROL_MASK:
                if gtk.gdk.keyval_name(event.keyval) == "Up":              # Ctrl + Up Arrow
                    if self.hindex > 0:
                        if self.hindex == len(self.history) - 1:
                            text = self.msg.get_text(self.msg.get_start_iter(), self.msg.get_end_iter(), False)
                            if text != self.history[-1]:
                                self.history.append([False,text])
                        self.hindex = self.hindex - 1
                        self.msg.set_text(self.history[self.hindex][1])
                        
                elif gtk.gdk.keyval_name(event.keyval) == "Down":          # Ctrl + Down Arrow
                    if self.hindex < len(self.history) - 1:
                        self.hindex = self.hindex + 1
                        self.msg.set_text(self.history[self.hindex][1])
                        
                elif gtk.gdk.keyval_name(event.keyval) == "t":                     # Ctrl + T
                    if self.is_tex_tag_open: self.msg.insert_at_cursor('</tex>')
                    else: self.msg.insert_at_cursor('<tex>')
                    self.is_tex_tag_open = not self.is_tex_tag_open

